package handler

import (
	"car-order-mgr/cache"
	"car-order-mgr/model"
	"car-order-mgr/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func RoleNodeList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var list []model.RoleNodeList
	/*
	 SELECT
	   roles.role_name RoleName,
	   nodes.node_name NodeName
	 FROM
	   role_nodes
	   LEFT JOIN roles ON role_nodes.rid = roles.id
	   LEFT JOIN nodes ON role_nodes.nid = nodes.id
	*/
	redis_key := "role_node_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("role_nodes").
			Select(
				"roles.role_name RoleName",
				"nodes.node_name NodeName",
			).
			Joins("LEFT JOIN roles ON role_nodes.rid = roles.id").
			Joins("LEFT JOIN nodes ON role_nodes.nid = nodes.id").
			Offset(offset).Limit(size).Find(&list)
		jaonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jaonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var total int64
	model.DB.Model(&model.RoleNode{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "角色权限展示成功",
		"data":  list,
		"total": total,
	})
	return
}

func UserRoleList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	/*
		SELECT
		  users.username AS Username,
		  users.`password` PASSWORD,
		  roles.role_name RoleName
		FROM
		  user_roles
		  LEFT JOIN users ON user_roles.uid = users.id
		  LEFT JOIN roles ON user_roles.rid = roles.id
	*/
	var list []model.UserRoleList
	model.DB.Table("user_roles").
		Select(
			"users.username AS Username",
			"users.`password` Password",
			"roles.role_name RoleName",
		).
		Joins("LEFT JOIN users ON user_roles.uid = users.id").
		Joins("LEFT JOIN roles ON user_roles.rid = roles.id").
		Offset(offset).Limit(size).Find(&list)
	var total int64
	model.DB.Model(&model.UserRole{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "用户角色查询成功",
		"data":  list,
		"total": total,
	})
	return
}

func RoleNode(c *gin.Context) {
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON nodes.id = role_nodes.nid
		WHERE role_nodes.rid=1
	*/
	rid := c.Query("rid")
	var node []model.Node
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where("role_nodes.rid=?", rid).
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
	return
}

func UserRole(c *gin.Context) {
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
		WHERE user_roles.uid=1
	*/
	uid := c.Query("uid")
	var role []model.Role
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid=?", uid).
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"mag":  "查询成功",
		"data": role,
	})
}

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"mag":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次已禁封两小时",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"mag":  "密码错误三次禁封两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"mag":  "密码错误请重新输入",
		})
		return
	}
	token := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"data":  user,
		"token": token,
	})
}
func Info(c *gin.Context) {
	uid, _ := c.Get("uid")
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"uid":  uid,
	})
	return
}
